package org.dut.community.controller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dut.community.annotation.LoginRequired;
import org.dut.community.entity.User;
import org.dut.community.service.UserService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SecurityContextLogoutHandler securityContextLogoutHandler;

    @Value("${server.servlet.context-path}")
    private String contextPath; // 项目名

    // 注册页面
    @RequestMapping(path = "/register",method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

    // 提交注册信息
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String register(Model model, User user){
        Map<String,Object> map = userService.register(user);
        // map为空，则注册没有问题
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","注册成功，我们已经发送了一封激活邮件，请尽快激活！");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else{
            // 前端判断 Msg 是否为空
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }
    }

    // 激活账号
    @RequestMapping(path = "/activation/{userId}/{code}",method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code){
        int result = userService.activation(userId,code);
        if(result == CommunityConstant.ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功，您的账号已经可以正常使用！");
            model.addAttribute("target","/login");
        }else if(result == CommunityConstant.ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作，该账号已经激活过了！");
            model.addAttribute("target","/index");
        }else{
            model.addAttribute("msg","激活失败，您提供的激活码错误！");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    // 登录页面
    @RequestMapping(path = "/login",method = RequestMethod.GET)
    public String getLoginPage(){
        return "/site/login";
    }

    /**
     * 提交登录信息
     * @param code 验证码
     * @param rememberMe 是否记住密码，设置不同的过期时间
     * @param model 模型，用于传递数据，动态加载前端网页
     * @param owner 唯一标识用户
     * @param response 响应，用于设置cookie
     */
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    public String login(String username,String password,String code,boolean rememberMe,
                        Model model,@CookieValue("owner") String owner, HttpServletResponse response){
        // 验证码判断
        String kaptcha = null;
        if(StringUtils.isNoneBlank(owner)){
            kaptcha = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getKaptchaKey(owner));
        }
        if(StringUtils.isBlank(kaptcha) ||StringUtils.isBlank(code)|| !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码错误！");
            return "/site/login";
        }
        // 登录
        int expiredSeconds = rememberMe ? CommunityConstant.REMEMBER_EXPIRED_SECONDS :
                CommunityConstant.DEFAULT_EXPIRED_SECONDS;
        Map<String,String> map = userService.login(username,password,expiredSeconds);
        if(map.containsKey("ticket")){
            // 登录成功，将ticket存入cookie
            Cookie cookie = new Cookie("ticket",map.get("ticket"));
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            // 登录成功，跳转到首页(重定向)
            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "/site/login";
        }
    }

    // 登出,从Cookie中获得数据
    @LoginRequired
    @RequestMapping(path="/logout",method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket, HttpServletResponse response,
                         HttpServletRequest request, Authentication authentication){
        userService.logout(ticket);
        // 登出,清理SecurityContext
        securityContextLogoutHandler.logout(request, response, authentication);

        return "redirect:/login";
    }

    // 加载验证码
    @RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
    public void getKaptcha(HttpSession session, HttpServletResponse response){
        // 生成验证码
        String text = kaptchaProducer.createText();
        // 生成图片
        BufferedImage image = kaptchaProducer.createImage(text);
        // 验证码存入session
//        session.setAttribute("kaptcha",text);
//        response.setContentType("image/png");

        // 验证码归属
        String owner = CommunityUtil.getUUID();
        Cookie cookie = new Cookie("owner",owner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath); // 整个项目路径下有效
        response.addCookie(cookie);
        // 验证码存入redis
        String redisKey = RedisKeyUtil.getKaptchaKey(owner);
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);

        response.setContentType("image/png");
        try{
            OutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            log.error("响应验证码失败："+e.getMessage());
        }

    }

    // 忘记密码页面
    @RequestMapping(path = "/forget",method = RequestMethod.GET)
    public String getForgetCode(){
        return "/site/forget";
    }

    // 忘记密码--获取验证码
    @ResponseBody
    @RequestMapping(path = "/forget/code",method = RequestMethod.GET)
    public String getForgetCode(String email){
        Map<String,String> map = userService.getForgetCode(email);
        if(map.containsKey("verifyCode")){
            return CommunityUtil.getJSONString(0);
        }else{
            return CommunityUtil.getJSONString(1, map.get("emailMsg"));
        }
    }

    // 忘记密码--重置密码
    @RequestMapping(path = "forgetPassword",method = RequestMethod.POST)
    public String forgetPassword(String email,String verifyCode,String password,Model model){
        String code = (String)redisTemplate.opsForValue().get(RedisKeyUtil.getForgetKey(email));
        if(StringUtils.isBlank(code) || StringUtils.isBlank(verifyCode) || !code.equalsIgnoreCase(verifyCode)){
            model.addAttribute("verifyCodeMsg","验证码错误或过期！");
            return "/site/forget";
        }
        Map<String,String> map = userService.resetPassword(email,password);
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","密码重置成功！");
            model.addAttribute("target","/login");
            return "/site/operate-result";
        }else{
            model.addAttribute("emailMsg",map.get("emailMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "/site/forget";
        }
    }

}
